//
//  LGWebViewController.m
//  LuxuryGoods
//
//  Created by 刘星辰 on 2018/5/19.
//  Copyright © 2018年 Future. All rights reserved.
//

#import "LGWebViewController.h"
#import <Masonry/Masonry.h>
#import "UIPageDefines.h"
#import "NSString+Tool.h"

@interface LGWebViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, strong) NSMutableDictionary *jsMessageBlocks;
@end

@implementation LGWebViewController
@synthesize webView = _webView;
- (void)dealloc {
    [_jsMessageBlocks removeAllObjects];
    _jsMessageBlocks = nil;
    //
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
    [self _clearCache];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = _webTitle;
    
    _jsMessageBlocks = [NSMutableDictionary dictionary];
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
    config.userContentController = [[WKUserContentController alloc]init];
    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-NAVIGATOR_HEIGHT) configuration:config];
    _webView.navigationDelegate = self;
    _webView.UIDelegate = self;
    _webView.contentMode = UIViewContentModeScaleAspectFit;
    _webView.scrollView.bounces = YES;
    _webView.scrollView.showsHorizontalScrollIndicator = NO;
    _webView.scrollView.showsVerticalScrollIndicator = NO;
    [_webView sizeToFit];
    //    webview进度条视图
    _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 3)];
    [_webView addSubview:_progressView];
    [_webView bringSubviewToFront:_progressView];
    [self.view addSubview:_webView];
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    // 增加一个观察者
    [_webView addObserver:self
               forKeyPath:@"estimatedProgress"
                  options:NSKeyValueObservingOptionNew
                  context:nil];
    [_webView addObserver:self
               forKeyPath:@"title"
                  options:NSKeyValueObservingOptionNew
                  context:nil];
    [self initialRequest];
    
    
    [self makeLeftItem];
    
}

- (void)initialRequest
{
    if (_localHtmlString.length != 0) {
        [_webView loadHTMLString:_localHtmlString baseURL:nil];
    } else if (_localHtmlFile.length != 0) {
        NSString* path = [[NSBundle mainBundle] pathForResource:_localHtmlFile ofType:@"html"];
        NSURL* url = [NSURL fileURLWithPath:path];
        NSURLRequest* request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:15];
        [_webView loadRequest:request];
    } else {
        NSString *urlStr = ([self hasChinese:_webUrl])?([_webUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]):(_webUrl);
        NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:15];
        [_webView loadRequest:request];
    }
}


- (void)removeFromParentViewController
{
    [self _removeScriptMessageHandler];
    [super removeFromParentViewController];
}
- (void)popOrDismiss {
    if (_webView.canGoBack) {
        [_webView goBack];
    } else {
        [super popOrDismiss];
        [self _removeScriptMessageHandler];
    }
}


#pragma mark - 制作左边按钮
- (void)makeLeftItem {
    //    UIButton *leftButton = [[UIButton alloc]init];
    //    leftButton.frame = CGRectMake(0, 0, 20, 40);
    //    leftButton.tag = 10;
    //    leftButton.titleLabel.font = TEXT_FONT_15;
    //    [leftButton setImage:[UIImage imageNamed:@"ico_return_normal"]
    //                forState:UIControlStateNormal];
    //    [leftButton setTitleColor:TEXT_COLOR_1
    //                     forState:UIControlStateNormal];
    //    leftButton.imageEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0);
    //    [leftButton addTarget:self
    //                   action:@selector(popOrDismiss)
    //         forControlEvents:UIControlEventTouchUpInside];
    
    //    _closeButton = [[UIButton alloc]init];
    //    _closeButton.frame = CGRectMake(0, 0, 35, 40);
    //    _closeButton.titleLabel.font = TEXT_FONT_15;
    //    _closeButton.tag = 20;
    //    _closeButton.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    //    [_closeButton setTitle:@"关闭" forState:UIControlStateNormal];
    //    [_closeButton setTitleColor:WHITE_COLOR
    //                       forState:UIControlStateNormal];
    //    [_closeButton addTarget:self
    //                     action:@selector(closeAction)
    //           forControlEvents:UIControlEventTouchUpInside];
    //    _closeButton.hidden = YES;
    //    NSArray<UIBarButtonItem *> *leftItems = @[[[UIBarButtonItem alloc] initWithCustomView:leftButton],
    //                                              [[UIBarButtonItem alloc] initWithCustomView:_closeButton]];
    //
    //    [self.navigationItem setLeftBarButtonItems:leftItems animated:YES];
    //    [self.navigationItem setLeftBarButtonItems:@[[[UIBarButtonItem alloc] initWithCustomView:leftButton]] animated:YES];
}


#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString *scheme = navigationAction.request.URL.scheme;
    if ([@"ngari" isEqualToString:scheme])
    {
        NSString *action = navigationAction.request.URL.resourceSpecifier;
        if ([@"close" isEqualToString:action]) {
            decisionHandler(WKNavigationActionPolicyCancel);
            [self.navigationController popViewControllerAnimated:YES];
        }else if ([@"back" isEqualToString:action]){
            decisionHandler(WKNavigationActionPolicyCancel);
            [self.navigationController popViewControllerAnimated:YES];
        }
    } else if ([@"tel" isEqualToString:scheme])
    {
        UIApplication *app = [UIApplication sharedApplication];
        if ([app canOpenURL:navigationAction.request.URL]) {
            [app openURL:navigationAction.request.URL];
        }
        decisionHandler(WKNavigationActionPolicyCancel);
    }
    else if ([@"itms-services" isEqualToString:scheme])
    {
        UIApplication *app = [UIApplication sharedApplication];
        if ([app canOpenURL:navigationAction.request.URL]) {
            [app openURL:navigationAction.request.URL];
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    }
    
    
    //    NSLog(@"%@",[navigationAction.request.URL absoluteString]);
    
    //    NSString* orderInfo = [[AlipaySDK defaultService]fetchOrderInfoFromH5PayUrl:[navigationAction.request.URL absoluteString]];
    //    if (orderInfo.length > 0)
    //    {
    //
    //    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    //    if (self.webTitle.length <= 0 && ![Public isNotBlankString:self.title]) {
    //        self.title = [webView.title isEqualToString:@"纳里健康"] ? [HospitalManager sharedHospitalManager].HospitalName : webView.title;
    //    }
    //
    ////    if (_webView.canGoBack) {
    ////        _closeButton.hidden = NO;
    ////    } else {
    ////        _closeButton.hidden = YES;
    ////    }
    //
    //    //此时，来判断当前的网络状态
    //    if (kNetworkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
    //        [self showNoContentViewWithHint:@"网络不健康,请检查网络" refreshButtonText:nil andRefreshButton:nil onView:self.view andPlaceHolderImageImage:[UIImage imageNamed:@"empty"]];
    //        if (self.loadedFinish)
    //        {
    //            self.loadedFinish(webView,navigation, [NSError errorWithDomain:@"网络不健康,请检查网络" code:609 userInfo:nil]);
    //        }
    //    }
    //    else
    //    {
    //        if (self.loadedFinish)
    //        {
    //            self.loadedFinish(webView,navigation, nil);
    //        }
    //    }
    
}


- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"加载失败");
//    [self showNoContentViewWithHint:@"网络不健康,请检查网络" refreshButtonText:nil andRefreshButton:nil onView:self.view andPlaceHolderImageImage:[UIImage imageNamed:@"empty"]];
    if (self.loadedFinish)
    {
        self.loadedFinish(webView,navigation, [NSError errorWithDomain:@"网络不健康,请检查网络" code:609 userInfo:nil]);
    }
}

#pragma mark - WKScriptMessageHandler methods

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    void (^block)(id) = [_jsMessageBlocks objectForKey:message.name];
    if (block) {
        block(message.body);
    }
}


#pragma mark - Actions

- (void)closeAction {
    [super popOrDismiss];
    [self _removeScriptMessageHandler];
}


#pragma mark- 进度条KVO监听

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,id> *)change
                       context:(void *)context
{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        
        self.progressView.progress = self.webView.estimatedProgress;
        // 加载完成
        if (self.webView.estimatedProgress  >= 1.0f ) {
            
            [UIView animateWithDuration:0.25f animations:^{
                self.progressView.alpha = 0.0f;
                self.progressView.progress = 0.0f;
            }];
            
        }else{
            self.progressView.alpha = 1.0f;
        }
    }else if ([keyPath isEqualToString:@"title"]){
        if (object == self.webView) {
            self.title = (![self.webView.title isNotBlank])?(AppName):(self.webView.title);
        }else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    
    
}


#pragma mark - Private methods

/**
 防止循环引用 需要remove
 */
- (void)_removeScriptMessageHandler {
    for (NSString *msg in _jsMessageBlocks) {
        [_webView.configuration.userContentController removeScriptMessageHandlerForName:msg];
    }
}


/**
 清理缓存的方法，这个方法会清除缓存类型为HTML类型的文件
 */
- (void)_clearCache {
    /* 取得Library文件夹的位置*/
    NSString *libraryDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask, YES)[0];
    /* 取得bundle id，用作文件拼接用*/
    NSString *bundleId  =  [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleIdentifier"];
    /*
     * 拼接缓存地址，具体目录为App/Library/Caches/你的APPBundleID/fsCachedData
     */
    NSString *webKitFolderInCachesfs = [NSString stringWithFormat:@"%@/Caches/%@/fsCachedData",libraryDir,bundleId];
    
    NSError *error;
    /* 取得目录下所有的文件，取得文件数组*/
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //    NSArray *fileList = [[NSArray alloc] init];
    //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
    NSArray *fileList = [fileManager contentsOfDirectoryAtPath:webKitFolderInCachesfs error:&error];
    /* 遍历文件组成的数组*/
    for(NSString * fileName in fileList){
        /* 定位每个文件的位置*/
        NSString * path = [[NSBundle bundleWithPath:webKitFolderInCachesfs] pathForResource:fileName ofType:@""];
        /* 将文件转换为NSData类型的数据*/
        NSData * fileData = [NSData dataWithContentsOfFile:path];
        /* 如果FileData的长度大于2，说明FileData不为空*/
        if(fileData.length >2){
            /* 创建两个用于显示文件类型的变量*/
            int char1 =0;
            int char2 =0;
            
            [fileData getBytes:&char1 range:NSMakeRange(0,1)];
            [fileData getBytes:&char2 range:NSMakeRange(1,1)];
            /* 拼接两个变量*/
            NSString *numStr = [NSString stringWithFormat:@"%i%i",char1,char2];
            /* 如果该文件前四个字符是6033，说明是Html文件，删除掉本地的缓存*/
            if([numStr isEqualToString:@"6033"]){
                [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@",webKitFolderInCachesfs,fileName]error:&error];
                continue;
            }
        }
    }
}


#pragma mark - js调oc方法 methods
- (void)addScriptMessageHandleBlock:(void(^)(id body))handle name:(NSString *)name{
    [_jsMessageBlocks addEntriesFromDictionary:@{name: handle}];
    [_webView.configuration.userContentController addScriptMessageHandler:self name:name];
}

#pragma makr - oc调js方法 methods
- (void)calledScriptMethod:(NSString *)methodName parameter:(id)parameter completionHandler:(void(^)(id bdoy,NSError *error))handle
{
    NSString *jsParameter = ([parameter isKindOfClass:[NSDictionary class]])?([self convertToJsonData:parameter]):([NSString stringWithFormat:@"%@",parameter]);
    
    NSString *js = [NSString stringWithFormat:@"%@(%@)",methodName,jsParameter];
    [_webView evaluateJavaScript:js completionHandler:handle];
}



/**
 判断是否含有中文
 */
- (BOOL)hasChinese:(NSString *)str
{
    for(int i=0; i< [str length];i++)
    {
        
        int a = [str characterAtIndex:i];
        
        if( a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
    }
    
    return NO;
    
}

/**
 字典转json
 */
-(NSString *)convertToJsonData:(NSDictionary *)dict

{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    // js 里面的alert实现，如果不实现，网页的alert函数无效
    [self showAlertWithTitle:nil message:message leftButtonTitle:nil rightButtonTitle:@"确定" leftBlock:nil rightBlock:^{
        completionHandler();
    }];
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    //  js 里面的alert实现，如果不实现，网页的alert函数无效  ,
    //    [NHAlertView showAlertWithTitle:nil message:message leftButtonTitle:@"取消" rightButtonTitle:@"确定" leftBlock:^{
    //        completionHandler(NO);
    //    } rightBolck:^{
    //        completionHandler(YES);
    //    }];
    
    [self showAlertWithTitle:nil message:message leftButtonTitle:@"取消" rightButtonTitle:@"确定" leftBlock:^{
        completionHandler(NO);
    } rightBlock:^{
        completionHandler(YES);
    }];
}

- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message leftButtonTitle:(NSString *)leftTitle rightButtonTitle:(NSString *)rightTitle leftBlock:(void(^)(void))left rightBlock:(void(^)(void))right
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        if (left)
        {
            left();
        }
    }];
    
    UIAlertAction *sureAction  = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (right)
        {
            right();
        }
    }];
    
    [alert addAction:cancelAction];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}
@end
